"""Diceware passphrase generator for dwgen.

Copyright 2015 Mattias Jakobsson

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""

import random

import pkg_resources


def get_word_dict(language):
    """Return a dictionary with Diceware words for the given *language*."""
    def parseline(line):
        dices, word = line.split()
        return int(dices), word.decode('utf-8')

    resource = 'data/{0}.wordlist.asc'.format(language)
    if not pkg_resources.resource_exists('dwgen', resource):
        raise ValueError("unsupported language '{0}'".format(language))
    with pkg_resources.resource_stream('dwgen', resource) as lines:
        return dict(map(parseline, lines))


def generate_password(language='en'):
    """Choose a word from the Diceware list for the given *language*."""
    word_dict = get_word_dict(language)
    gen = random.SystemRandom()
    dices = sum(gen.randrange(1, 7) * 10**p for p in range(5))
    return word_dict[dices]


def generate_passphrase(n, language='en', separator=' '):
    """Generate a *n* word passphrase using the Diceware method."""
    return separator.join(generate_password(language) for _ in range(n))
